package com.ruoyi.sysem.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.sysem.demo.ocr_idcard;
import com.ruoyi.sysem.domain.CreditUser;
import com.ruoyi.sysem.domain.IdentityUser;
import com.ruoyi.sysem.service.ICreditUserService;
import com.ruoyi.sysem.service.IIdentityUserService;
import com.ruoyi.sysem.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户身份信息Controller
 * 
 * @author ruoyi
 * @date 2022-12-15
 */
@RestController
@RequestMapping("/user/cuser")
public class IdentityUserController extends BaseController
{
    @Autowired
    private IIdentityUserService identityUserService;
    @Autowired
    private ICreditUserService creditUserService;

    /**
     * 查询用户身份信息列表
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/list")
    public TableDataInfo list(IdentityUser identityUser)
    {
        startPage();
        List<IdentityUser> list = identityUserService.selectIdentityUserList(identityUser);
        return getDataTable(list);
    }

    /**
     * 导出用户身份信息列表
     */
    @RequiresPermissions("system:user:export")
    @Log(title = "用户身份信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, IdentityUser identityUser)
    {
        List<IdentityUser> list = identityUserService.selectIdentityUserList(identityUser);
        ExcelUtil<IdentityUser> util = new ExcelUtil<IdentityUser>(IdentityUser.class);
        util.exportExcel(response, list, "用户身份信息数据");
    }

    /**
     * 获取用户身份信息详细信息
     */
    @RequiresPermissions("system:user:query")
    @GetMapping(value = "query/{id}" +
            "")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(identityUserService.selectIdentityUserById(id));
    }

    /**
     * 新增用户身份信息
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户身份信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody IdentityUser identityUser)
    {
        return toAjax(identityUserService.insertIdentityUser(identityUser));
    }

    /**
     * 修改用户身份信息
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户身份信息", businessType = BusinessType.UPDATE)
    @PutMapping("edit")
    public AjaxResult edit(@RequestBody IdentityUser identityUser)
    {
        return toAjax(identityUserService.updateIdentityUser(identityUser));
    }

    /**
     * 删除用户身份信息
     */
    @RequiresPermissions("system:user:remove")
    @Log(title = "用户身份信息", businessType = BusinessType.DELETE)
	@DeleteMapping("remove/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(identityUserService.deleteIdentityUserByIds(ids));
    }

    /**
     * 身份验证
     * @param
     * @return
     */
    @PostMapping("/smqm")
    private AjaxResult Smqm(MultipartFile file) throws IOException {
        File file1 = new File("D:\\study\\"+file.getOriginalFilename());
        //file.transferTo(file1);
        String absolutePath = file1.getAbsolutePath();
        return ocr_idcard.aa(absolutePath);
    }


    /**
     * 调用失信人接口
     * @return
     */
    @PostMapping("/SxRy")
    public AjaxResult SxRy(@RequestBody Map<String, String> body){
        String host = "https://jumjokk.market.alicloudapi.com";
        String path = "/personal/disenforcement";
        String method = "POST";
        String appcode = "fb91964ff8864e639dc3769d5d50b1ed";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("idcard_number", body.get("cnum"));
        bodys.put("mobile_number", body.get("elphone"));
        bodys.put("name", body.get("cname"));
        try {

            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //System.out.println(response.toString());
            //获取response的body
           // System.out.println(EntityUtils.toString(response.getEntity()));
            String json=  EntityUtils.toString(response.getEntity());
            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readTree(json);
            JsonNode data = root.path("data");
            Map<String, String> map = mapper.convertValue(data, Map.class);
            if (map.size()>0) {
                CreditUser creditUser = new CreditUser();
                creditUser.setUid(Integer.valueOf(body.get("cid").toString()));
                List<CreditUser> creditUsers = creditUserService.selectCreditUserList(creditUser);
                creditUser.setCid(Long.parseLong(creditUsers.get(0).getCid().toString()));
                String caseCount = String.valueOf(map.get("caseCount"));
                int usernum = Integer.parseInt(caseCount);
                if (usernum<=0) {
                    creditUser.setCredit("true");
                    creditUserService.updateCreditUser(creditUser);
                } else {
                    creditUser.setCredit("false");
                    creditUserService.updateCreditUser(creditUser);
                }
                return AjaxResult.success(map);
            }else{
                return AjaxResult.error("请输入正确的信息");
            }
            //return AjaxResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查无此人");
    }



}
